package com.lagou.products.controller;

import com.lagou.domain.Products;
import com.lagou.products.service.ProductsService;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/products")
public class ProductsController {

    public static String topic = "product"; //kafka主题
    @Autowired
    private ProductsService productsService;
    @Autowired
    private KafkaProducer kafkaProducer;

    /**
     * 根据商品ID查询商品
     * @param id
     * @return
     */
    @GetMapping("/getProductsById/{id}")
    public Products getProductsById(@PathVariable Integer id){
        Products products = productsService.getProductsById(id);
        return products;
    }

    /**
     * 新增商品信息
     * @param products
     * @return
     */
    @PostMapping("addProducts")
    public Long addProducts(@RequestBody Products products){
        Integer affectNum = productsService.addProducts(products);
        if (affectNum == 1) {
            ProducerRecord<String, String> record = new ProducerRecord<>(topic,products.getId()+"");
            kafkaProducer.send(record);
            System.out.println("消息发送成功："+ products.getId());
            return products.getId();
        } else {
            return 0L;
        }
    }
}
